#include "app_mqtt.h"
#include "mqtt_client.h"
#include "esp_event.h"
#include "esp_netif.h"

#define MQTT_SERVER_URI "mqtt://broker.emqx.io"

char mqtt_pub_topic[64];
char mqtt_sub_topic[64];

static esp_mqtt_client_handle_t mqtt_client;
static bool mqtt_connected = false;

static void ip_event_handler(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
    if (event_id == IP_EVENT_STA_GOT_IP)
    {
        if (!mqtt_connected)
        {
            esp_mqtt_client_start(mqtt_client);
        }
    }
}

static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
    esp_mqtt_event_handle_t event = event_data;
    esp_mqtt_client_handle_t client = event->client;
    switch (event->event_id)
    {
    case MQTT_EVENT_CONNECTED:
        mqtt_connected = true;
        esp_mqtt_client_subscribe(client, mqtt_sub_topic, 0);
        break;
    case MQTT_EVENT_DISCONNECTED:
        mqtt_connected = false;
        break;
    default:
        break;
    }
}

void app_mqtt_send(char *data, int len)
{
    esp_mqtt_client_publish(mqtt_client, mqtt_pub_topic, data, len, 1, 0);
}

void app_mqtt_init()
{
    const esp_mqtt_client_config_t mqtt_cfg = {
        .broker.address.uri = MQTT_SERVER_URI,
    };
    sprintf(mqtt_pub_topic, "esp32/luodelin/pub");
    sprintf(mqtt_sub_topic, "esp32/luodelin/sub");
    mqtt_client = esp_mqtt_client_init(&mqtt_cfg);
    esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &ip_event_handler, NULL);
    esp_mqtt_client_register_event(mqtt_client, ESP_EVENT_ANY_ID, mqtt_event_handler, mqtt_client);
}
